package com.eq.controller;

import com.eq.dto.FileItem;
import com.eq.dto.PathRequest;
import com.eq.dto.RenameRequest;
import com.eq.util.PathChecker;
import java.io.IOException;
import com.eq.service.FileStorageService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/files")
public class FileController {

    @Autowired
    private FileStorageService storageService;

    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            storageService.store(file);
            return ResponseEntity.ok("File uploaded successfully");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body("Failed to upload file");
        }
    }

    @PostMapping("/list")
    public ResponseEntity<List<FileItem>> listUploadedFiles(@RequestBody PathRequest pathRequest) {
        try {
            String path = PathChecker.checkAndFixPath(pathRequest.getPath());
            if (path == null) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
            List<FileItem> files = storageService.loadAll(path)
                    .map(file_path -> {
                        try {
                            return storageService.getFileMetadata(file_path);
                        } catch (IOException e) {
                            throw new RuntimeException("Failed to get file metadata", e);
                        }
                    })
                    .collect(Collectors.toList());
            return ResponseEntity.ok(files);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
    }

    @PostMapping("/create-directory")
    public ResponseEntity<String> createDirectory(@RequestBody PathRequest pathRequest) {
        try {
            String path = PathChecker.checkAndFixPath(pathRequest.getPath());
            if (path == null) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
            storageService.createDirectory(path);
            return ResponseEntity.ok("Directory created successfully");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body("Failed to create directory");
        }
    }

    @PostMapping("/delete")
    public ResponseEntity<String> deleteFileOrDirectory(@RequestBody PathRequest pathRequest) {
        try {
            String path = PathChecker.checkAndFixPath(pathRequest.getPath());
            if (path == null) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
            storageService.delete(path);
            return ResponseEntity.ok("File or directory deleted successfully");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body("Failed to delete file or directory");
        }
    }

    @PostMapping("/rename")
    public ResponseEntity<String> renameFile(@RequestBody RenameRequest renameRequest) {
        try {
            String sourcePath = PathChecker.checkAndFixPath(renameRequest.getSourcePath());
            String targetPath = PathChecker.checkAndFixPath(renameRequest.getTargetPath());
            if (sourcePath == null || targetPath == null) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
            storageService.rename(sourcePath, targetPath);
            return ResponseEntity.ok("File renamed successfully");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body("Failed to rename file");
        }
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(String filePath) {
        try {
            String path = PathChecker.checkAndFixPath(filePath);
            if (path == null) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
            Resource file = storageService.loadAsResource(path);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=\"" + file.getFilename() + "\"")
                    .body(file);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
    }
}
